package org.example;

import bean.DB;
import bean.ResponseUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

@WebServlet("/ClearCartServlet")
public class ClearCartServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取当前用户ID
        String userIdStr = (String) request.getSession().getAttribute("userId");

        if (userIdStr == null) {
            // 如果用户未登录，重定向到登录页面
            ResponseUtils.sendResponse(response, "请先登录", "login.jsp");
            return;
        }

        Integer userId;
        try {
            // 转换用户ID为 Integer 类型
            userId = Integer.parseInt(userIdStr);
        } catch (NumberFormatException e) {
            // 如果转换失败，返回错误提示
            ResponseUtils.sendResponse(response, "无效的用户ID", "cart.jsp");
            return;
        }

        // 创建数据库连接
        DB db = new DB();
        String query = "DELETE FROM usercart WHERE user_id = ?";

        try (Connection conn = db.createConn(); PreparedStatement pstmt = conn.prepareStatement(query)) {
            pstmt.setInt(1, userId);

            // 执行删除操作
            int rowsAffected = pstmt.executeUpdate();

            if (rowsAffected > 0) {
                // 如果删除成功，提示用户并跳转到购物车页面
                ResponseUtils.sendResponse(response, "购物车已清空", "cart.jsp");
            } else {
                // 如果未删除任何记录
                ResponseUtils.sendResponse(response, "购物车为空，无法清空", "cart.jsp");
            }

        } catch (SQLException e) {
            // 处理数据库异常
            e.printStackTrace();
            ResponseUtils.sendResponse(response, "操作失败，数据库错误", "cart.jsp");
        }
    }
}
